<template>
    <div class="uploadBox">
      <!-- 返回主页 -->
      <div class="homeBox">
        <router-link to="/home/student">
          <el-button>返回学生信息列表</el-button>
        </router-link>
      </div>
      <!-- 上传文件按钮 -->
      <div class="buttonBox">
        <!--:auto-upload="false"选择文件后不自动上传
          action必须写（不写报错），但是可以不指定内容
           accept=".xlsx,.xls"：接受上传文件的类型
          :on-change="handle":文件上传成功和上传失败的回调函数
            
            -->
        <el-upload
          action
          accept=".xlsx,.xls"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handle"
        >
          <!-- slot="trigger" -->
          <el-button type="primary">选取excel文件 </el-button>
        </el-upload>
        <el-button type="success" @click="submit">采集数据提交</el-button>
      </div>
      <!--解析出来的数据 -->
      <div class="tableBox" v-show="show">
        <h3>
          以下是采集完成的数据，请您检查无误后，点击"采集数据提交"按钮上传至服务器。
        </h3>
        <el-table
          :data="Data.tableData"
          :default-sort="{ prop: 'sid', order: 'descending' }"
          style="width: 100%"
        >
          <el-table-column prop="sid" label="学号" align="center">
          </el-table-column>
          <el-table-column prop="name" label="姓名" align="center">
          </el-table-column>
          <el-table-column prop="sex" label="性别" align="center">
          </el-table-column>
          <el-table-column prop="age" label="年龄" align="center">
          </el-table-column>
  
          <el-table-column prop="sclass" label="班级" align="center">
          </el-table-column>
          <el-table-column prop="address" label="地址" align="center">
          </el-table-column>
          <el-table-column prop="phone" label="联系方式" align="center">
          </el-table-column>
        </el-table>
      </div>
    </div>
  </template>
  
  <script setup>
  import { reactive, ref } from "vue";
  import { ReadFile, character } from "@/utils/fileUtils";
  import xlsx from "xlsx";
  import { ElMessage } from "element-plus";
  import { addStudents } from "@/api/api.js";
  let Data = reactive({
    tableData: [],
  });
  let show = ref(false);
  const handle = async (ev) => {
    // 通过返回的文件信息进行判断，只有有文件才能执行
    console.log(ev);
    let file = ev.raw;
    if (!file) return;
    show.value = false;
  
    // 读取file文件中的二进制数据
    let data = await ReadFile(file);
    // 再用xlsx的插件读取二进制数据,并指定类型为binary
    let workbook = xlsx.read(data, { type: "binary" });
    console.log(workbook);
    //   变为json格式
    let worksheet = workbook.Sheets[workbook.SheetNames[0]]; //读取到excel中sheet1的数据 因为excel会分为（sheet1，sheet2，sheet3）
    data = xlsx.utils.sheet_to_json(worksheet);
  
    //   把读取出来的数据变为最后可以传递给服务器的数据
    let arr = [];
    data.forEach((item) => {
      let obj = {};
      // 循环有多少个字段
      for (let key in character) {
        if (!character.hasOwnProperty(key)) break;
        let v = character[key];
        let text = v.text;
        let type = v.type;
        v = item[text] || "";
        type === "string" ? (v = String(v)) : null;
        type === "number" ? (v = Number(v)) : null;
        obj[key] = v;
      }
      arr.push(obj);
    });
    //   展示数据
    show.value = true;
    Data.tableData = arr;
    console.log(arr);
  };
  
  // 提交数据给服务器
  const submit = async () => {
    // 如果没有数据给的提示
    if (Data.tableData.length <= 0) {
      ElMessage({
        message: "请先选择excel文件",
        type: "warning",
      });
      return;
    }
    // 提交完成给的提示
    const complete = () => {
      ElMessage({
        message: "数据已经上传完成",
        type: "success",
      });
      show.value = false;
    };
    // 需要把数据一条条传递给服务器
    let n = 0;
    let send = async () => {
      if (n > Data.tableData.length - 1) {
        // 都传递完了
        complete();
        return;
      }
      let body = Data.tableData[n];
      let result = await addStudents(body);
      console.log("result", result);
      if (result.data.status === 200) {
        // 成功
        n++;
      }
      send();
    };
    send();
  };
  </script>
  
  <style>
  </style>